<!-- 我的钱包 -->
<template>
	<view class="wallet-wrap">
		<!-- 钱包卡片 -->
		<view class="head_box u-flex u-row-center u-col-center">
			<view class="card-box">
				<view class="card-head u-flex u-col-center">
					<view class="card-title u-m-r-10">可提现金额（元）</view>
					<view @tap="showMoney = !showMoney" class="u-iconfont"
						:class="showMoney ? 'uicon-eye' : 'uicon-eye-off'" style="color: #fff;font-size: 46rpx;"></view>
				</view>
				<view class="money-num u-p-t-50">{{ showMoney ? userInfo.money || '0.00' : '*****' }}</view>
				<view class="button-group">
					<button v-if="initRecharge.enable ==='1'" class="u-reset-button withdraw-btn"
						@tap="$Router.push('/pages/user/wallet/top-up')">充值</button>
					<button class="u-reset-button withdraw-btn"
						@tap="$Router.push('/pages/user/wallet/withdraw')">提现</button>
					<button class="u-reset-button withdraw-btn" @tap="showModal = true">转赠</button>
				</view>
			</view>
		</view>
		<!-- 筛选 -->
		<u-sticky offset-top="0" :enable="true">
			<view class="filter-box u-flex u-row-between">
				<button class="u-reset-button date-btn u-flex" @tap="showCalendar = true">
					{{ selDateText }}
					<text class="u-iconfont uicon-arrow-down-fill u-m-l-20" style="color: #e5e5e5"></text>
				</button>
				<view class="total-box">收入￥{{ incomeMoney || '0.00' }} 支出￥{{ expendMoney || '0.00' }}</view>
			</view>
			<!-- 状态分类 -->
			<view class="u-flex nav-box">
				<view class="state-item u-flex-1 " v-for="(state, index) in statusList" :key="state.value"
					@tap="onTab(state.value)">
					<text class="state-title"
						:class="{ 'title-active': stateCurrent === state.value }">{{ state.name }}</text>
					<text class="underline" :class="{ 'underline-active': stateCurrent === state.value }"></text>
				</view>
			</view>
		</u-sticky>

		<!-- 钱包记录 -->
		<view class="wallet-list u-flex" v-for="item in walletLog" :key="item.id">
			<image class="head-img u-m-r-20" :src="item.avatar" mode=""></image>
			<view class="list-content">
				<view class="title-box u-flex u-row-between">
					<text class="title u-ellipsis-1">{{ item.type_name }}{{ item.title ? '-' + item.title : '' }}</text>
					<view class="money">
						<text v-if="item.wallet >= 0" class="add font-OPPOSANS">+{{ item.wallet }}</text>
						<text v-else class="minus font-OPPOSANS">{{ item.wallet }}</text>
					</view>
				</view>
				<text class="time">{{ $u.timeFormat(item.createtime, 'yyyy-mm-dd hh:MM') }}</text>
			</view>
		</view>
		<!-- 空置页 -->
		<shopro-empty v-if="isEmpty" marginTop="200rpx" :image="$IMG_URL + '/imgs/empty/no_data.png'" tipText="暂无数据~">
		</shopro-empty>
		<!-- 更多 -->
		<u-loadmore v-if="!isEmpty" height="80rpx" :status="loadStatus" icon-type="flower" color="#ccc" />
		<!-- 日期选择 -->
		<u-calendar v-model="showCalendar" ref="uCalendar" safeAreaInsetBottom mode="range" start-text="开始"
			end-text="结束" active-bg-color="#7063d2" active-color="#fff" range-bg-color="#e5e2ff" range-color="#7063d2"
			:customStyle="{ background: 'linear-gradient(90deg, #A36FFF, #5336FF)', boxShadow: '0 7rpx 11rpx 2rpx rgba(124, 103, 214, 0.34)' }"
			@change="selDate"></u-calendar>

		<!-- 转余额弹框 -->
		<view class="cu-modal bottom-modal" :class="{ show: showModal }" @tap="closeModal" style="z-index: 10080;">
			<view class="login-wrap cu-dialog form-wrap  safe-area-inset-bottom" @tap.stop
				style="border-radius: 20rpx 20rpx 0 0;">
				<view class="head-box u-m-b-40">
					<view class="head-title u-m-b-20">赠送积分</view>
					<view class="item-content u-flex u-col-center u-row-between">
						<view class="item-title">个人手机号</view>
						<view class="item-title">{{userInfo.mobile?userInfo.mobile:'未绑定'}}</view>
					</view>
				</view>
				<view class="form-item u-border-bottom">
					<view class="item-content u-flex u-col-center">
						<view class="item-title">手机号验证码</view>
						<u-input class="u-m-r-10 u-flex-1" @blur="checkValue($event, 'code')"
							@input="checkValue($event, 'code')" placeholder="请输入手机号验证码"
							:placeholderStyle="placeholderStyle" v-model="form['give'].data.code"
							type="number"></u-input>
						<button class=" code-btn code-btn-start" @tap="getSmsCode('give')">
							{{ codeText }}
						</button>
					</view>
					<view class="message-error">{{ form["give"].error.code || "" }}</view>
				</view>
				<view class="form-item u-border-bottom">
					<view class="item-content u-flex u-col-center">
						<view class="item-title">赠送的手机号</view>
						<u-input class="u-m-r-10 u-flex-1" @blur="checkValue($event, 'zj_mobile')"
							@input="checkValue($event, 'zj_mobile')" placeholder="请输入赠送的手机号"
							:placeholderStyle="placeholderStyle" v-model="form['give'].data.zj_mobile"></u-input>
					</view>
					<view class="message-error">{{ form["give"].error.zj_mobile || "" }}</view>
				</view>
				<view class="form-item u-border-bottom">
					<view class="item-content u-flex u-col-center">
						<view class="item-title">赠送的余额</view>
						<u-input class="u-m-r-10 u-flex-1" placeholder="请输入赠送的余额" :placeholderStyle="placeholderStyle"
							v-model="form['give'].data.zz_money" type="number"></u-input>
						<button class=" login-btn-start" @tap="giveSubmit">确认</button>
					</view>
					<view class="message-error">{{ form["give"].error.zz_money || "" }}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapGetters
	} from 'vuex';
	import schema from "@/uview-ui/libs/util/async-validator";
	import FormValidate from "@/shopro/validate/form";
	export default {
		data() {
			return {
				isEmpty: false,
				stateCurrent: 'all', //默认
				statusList: [{
						name: '全部',
						value: 'all'
					},
					{
						name: '收入',
						value: 'add'
					},
					{
						name: '支出',
						value: 'reduce'
					}
				],
				showMoney: true,
				//日期选择
				showCalendar: false,
				selDateText: '',
				walletLog: [], //钱包记录
				propsDate: '', //日期参数
				incomeMoney: '', //收入
				expendMoney: '', //支出
				loadStatus: 'loadmore', //loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
				currentPage: 1,
				lastPage: 1,
				showModal: false,
				codeText: "获取验证码",
				form: {
					give: {
						data: {
							mobile: "", // 手机号
							code: "", // 验证码
							zz_money: "", //转赠金额
							zj_mobile: "", // 密码
						},
						rules: {
							code: FormValidate.code,
							mobile: FormValidate.mobile,
							zj_mobile: FormValidate.mobile,

						},
						error: {
							mobile: "", // 手机号
							code: "", // 验证码
							zj_mobile: "", // 密码
						}
					},
				},
				codeText: "获取验证码",
				disabledCode: false,
			};
		},
		computed: {
			...mapGetters(['isLogin', 'userInfo', 'initRecharge'])
		},
		onShow() {
			this.form.give.data.mobile = this.userInfo.mobile
			this.isLogin && this.getUserInfo();
			this.getToday();
			this.currentPage = 1;
			this.lastPage = 1;
			this.walletLog = [];
			this.getWalletLog();
		},
		// 触底加载更多
		onReachBottom() {
			if (this.currentPage < this.lastPage) {
				this.currentPage += 1;
				this.getWalletLog();
			}
		},
		methods: {
			...mapActions(['getUserInfo']),
			//关闭弹窗
			closeModal() {
				this.showModal = false
				this.form.give.data = {
					mobile: "", // 手机号
					code: "", // 验证码
					zz_money: "", //转赠金额
					zj_mobile: "", // 密码
				}
			},
			// 获取短信验证码
			getSmsCode(type) {
				const that = this;
				if (!that.disabledCode) {
					that.$http(
						"common.smsSend", {
							mobile: that.form['give'].data.mobile,
							event: 'zz'
						},
						"获取验证码中..."
					).then(res => {
						if (res.code === 1) {
							that.codeChange();
							that.$u.toast("验证码已发送，请注意查收短信");
						} else {
							that.$u.toast(res.msg);
						}
					});
				} else {
					that.$u.toast("请稍后再试");
				}
			},
			// 倒计时
			codeChange() {
				if (this.disabledCode) return;
				this.disabledCode = true;
				let n = 60;
				this.codeText = n + "s";
				const run = setInterval(() => {
					n -= 1;
					if (n < 0) {
						clearInterval(run);
					}
					this.codeText = n + "s";
					if (this.codeText < 0 + "s") {
						this.disabledCode = false;
						this.codeText = "重新获取";
					}
				}, 1000);
			},
			// 检测
			checkValue(e, key) {
				this.validation(key);
			},
			// 校验数据
			validation(key, callback = () => {}) {
				let that = this;
				//拿到需要校验的数据
				let fieldValue = this.form['give'].data[key];
				//拿到需要检验的规则
				let rules = this.form['give'].rules[key];
				// 判空
				if (!rules || rules.length === 0) {
					return callback("");
				}
				// 设置当前的装填，标识为校验中
				let validateState = "validating";
				// 调用async-validator的方法
				let validator = new schema({
					[key]: rules
				});
				// 校验
				validator.validate({
						[key]: fieldValue
					}, {
						firstFields: true
					},
					(errors, fields) => {
						// 记录状态和报错信息
						validateState = !errors ? "success" : "error";
						let validateMessage = errors ? errors[0].message : "";
						that.form['give'].error[key] = validateMessage;
						callback(validateMessage);
					}
				);
			},
			validateAll(callback) {
				let that = this;
				return new Promise(resolve => {
					// 对当前所有表单检验
					let valid = true; // 默认通过
					let count = 0; // 用于标记是否检查完毕
					let errorArr = []; // 存放错误信息
					let curFormData = that.form['give'].data;
					console.log(curFormData)
					Object.keys(curFormData).map(field => {
						that.validation(field, error => {
							// 如果回调有error
							if (error) {
								valid = false;
								errorArr.push(error);
							}
							if (++count === Object.keys(curFormData).length) {
								resolve(valid);
								if (errorArr.length) {
									this.$u.toast(errorArr[0]);
								}
								if (typeof callback == "function") callback(valid);
							}
						});
					});
				});
			},
			// 转赠
			async giveSubmit() {
				let that = this;
				(await that.validateAll()) && that.$http(
						"user.zz_new_money", {
							mobile: that.form['give'].data.mobile,
							zj_mobile: that.form["give"].data.zj_mobile,
							code: that.form["give"].data.code,
							zz_money: that.form["give"].data.zz_money
						},
						"转赠中..."
					)
					.then(res => {
						if (res.code === 1) {
							that.$u.toast(res.msg);
							that.closeModal();
							that.walletLog = [];
							that.currentPage = 1;
							that.getWalletLog();
							that.$store.dispatch('getUserInfo');
						}
					});
			},
			//  今日
			getToday() {
				let now = new Date();
				let dateText = `${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()}`;
				this.selDateText = `${now.getFullYear()}.${now.getMonth() + 1}.${now.getDate()}`;
				this.propsDate = `${dateText}-${dateText}`;
			},
			// tab切换
			onTab(state) {
				if (this.stateCurrent !== state) {
					this.stateCurrent = state;
					this.currentPage = 1;
					this.lastPage = 1;
					this.walletLog = [];
					this.getWalletLog();
				}
			},
			// 日期选择
			selDate(e) {
				console.log(e, 999)
				this.walletLog = [];
				this.currentPage = 1;
				this.lastPage = 1;
				this.selDateText = `${e.startYear}.${e.startMonth}.${e.startDay}-${e.endYear}.${e.endMonth}.${e.endDay}`;
				let dateText = `${e.startYear}/${e.startMonth}/${e.startDay}-${e.endYear}/${e.endMonth}/${e.endDay}`;
				this.propsDate = dateText;
				this.getWalletLog();
				this.$refs.uCalendar.init();
			},
			// 钱包明细
			getWalletLog() {
				let that = this;
				that.loadStatus = 'loading';
				that.$http('money.walletLog', {
					wallet_type: 'money',
					status: that.stateCurrent,
					date: that.propsDate,
					page: that.currentPage
				}).then(res => {
					if (res.code === 1) {
						that.walletLog = [...that.walletLog, ...res.data.wallet_logs.data];
						that.incomeMoney = res.data.income;
						that.expendMoney = Math.abs(res.data.expend);
						that.isEmpty = !that.walletLog.length;
						that.lastPage = res.data.wallet_logs.last_page;
						that.loadStatus = that.currentPage < res.data.wallet_logs.last_page ? 'loadmore' :
							'nomore';
					}
				});
			}
		}
	};
</script>

<style lang="scss">
	// 钱包记录
	.wallet-list {
		width: 750rpx;
		padding: 30rpx;
		background-color: #ffff;
		border-bottom: 1rpx solid #eeeeee;

		.head-img {
			width: 70rpx;
			height: 70rpx;
			border-radius: 50%;
			background: #ccc;
		}

		.list-content {
			justify-content: space-between;
			align-items: flex-start;
			flex: 1;

			.title {
				font-size: 28rpx;
				color: #333;
				width: 400rpx;
			}

			.time {
				color: #c0c0c0;
				font-size: 22rpx;
			}
		}

		.money {
			font-size: 28rpx;
			font-weight: bold;

			.add {
				color: #7063d2;
			}

			.minus {
				color: #333333;
			}
		}
	}

	// 钱包
	.head_box {
		width: 750rpx;
		background-color: #fff;
		padding: 30rpx 0;

		.card-box {
			width: 690rpx;
			min-height: 300rpx;
			padding: 40rpx;
			background: url($IMG_URL+'/imgs/user/money_wallet_bg.png') no-repeat;
			background-size: 100% 100%;
			box-shadow: 1rpx 5rpx 16rpx 0 rgba(94, 73, 195, 0.81);
			border-radius: 30rpx;
			overflow: hidden;
			position: relative;

			.card-head {
				color: #fff;
				font-size: 30rpx;
			}

			.money-num {
				font-size: 70rpx;
				line-height: 70rpx;
				font-weight: 500;
				color: #ffffff;
			}

			.reduce-num {
				font-size: 26rpx;
				font-weight: 400;
				color: #ffffff;
			}

			.button-group {
				display: flex;
				align-items: center;
				flex: 1;
				margin-top: 20rpx;
				.withdraw-btn {
					width: 120rpx;
					height: 60rpx;
					line-height: 60rpx;
					background: #ffffff;
					border-radius: 30px;
					font-size: 24rpx;
					font-weight: 500;
					color: #5848c4;
					margin-right: 20rpx;
				}

				.topup-btn {
					width: 120rpx;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 30px;
					font-size: 24rpx;
					font-weight: 500;
					color: #fff;
					border: 1px solid #fff;
					margin-right: 20rpx;
				}
			}


		}
	}

	// 筛选

	.filter-box {
		height: 120rpx;
		padding: 0 30rpx;
		background-color: #f6f6f6;

		.date-btn {
			background-color: #fff;
			line-height: 54rpx;
			border-radius: 27rpx;
			padding: 0 20rpx;
			font-size: 24rpx;
			font-weight: 500;
			color: #666666;
		}

		.total-box {
			font-size: 24rpx;
			font-weight: 500;
			color: #999999;
		}
	}

	// 分类
	.state-item {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		border-bottom: 1rpx solid rgba(#999, 0.5);

		.state-title {
			color: #666;
			font-weight: 500;
			font-size: 28rpx;
			line-height: 90rpx;
		}

		.title-active {
			color: #333;
		}

		.underline {
			display: block;
			width: 68rpx;
			height: 4rpx;
			background: #fff;
			border-radius: 2rpx;
		}

		.underline-active {
			background: #5e49c3;
			display: block;
			width: 68rpx;
			height: 4rpx;
			border-radius: 2rpx;
		}
	}
	.login-btn-start {
		width: 158rpx;
		line-height: 56rpx;
		background: linear-gradient(90deg, #e9b461, #eecc89);
		border-radius: 28rpx;
		font-size: 26rpx;
		font-weight: 500;
		color: #ffffff;
	}
	
	
	.login-wrap {
		padding: 50rpx 34rpx;
		min-height: 650rpx;
		background-color: #fff;
	
		.head-box {
			.head-title {
				min-width: 160rpx;
				font-size: 36rpx;
				font-weight: bold;
				color: #333333;
				line-height: 36rpx;
			}
			.item-title{
				font-weight: bold;
				color: #333333;
				line-height: 28rpx;
				font-size: 28rpx;
			}
			.head-title-active {
				width: 160rpx;
				font-size: 32rpx;
				font-weight: 600;
				color: #999;
				line-height: 36rpx;
			}
	
			.head-title-animation {
				animation-name: title-animation;
				animation-duration: 0.1s;
				animation-timing-function: ease-out;
				animation-fill-mode: forwards;
			}
	
			.head-title-line {
				position: relative;
	
				&::before {
					content: "";
					width: 1rpx;
					height: 34rpx;
					background-color: #e4e7ed;
					position: absolute;
					left: -30rpx;
					top: 50%;
					transform: translateY(-50%);
				}
			}
	
			.head-subtitle {
				font-size: 26rpx;
				font-weight: 400;
				color: #c2c7cf;
				text-align: left;
				display: flex;
			}
		}
	
		.code-btn[disabled] {
			background-color: #fff;
		}
	
		.code-btn-start {
			width: 200rpx;
			line-height: 56rpx;
			border: 1rpx solid #e9b766;
			border-radius: 28rpx;
			font-size: 26rpx;
			font-weight: 400;
			color: #e9b766;
			opacity: 0.5;
		}
	
	}
	.form-wrap {
		.form-item {
			display: flex;
			flex-direction: column;
			font-size: 28rpx;
			padding: 20rpx 0;
			color: $u-main-color;
			box-sizing: border-box;
			line-height: $u-form-item-height;
			width: 100%;
	
			.item-title {
				width: 200rpx;
				font-size: 30rpx;
				color: #333;
				font-weight: 600;
				text-align: left;
			}
	
			.message-error {
				text-align: left;
				font-size: 24rpx;
				line-height: 24rpx;
				color: $u-type-error;
				margin-top: 12rpx;
				margin-left: 200rpx;
			}
		}
	}
</style>